﻿using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace OotsDownloader.Forms
{
    public partial class OotsDownloader : Form
    {
        readonly WebClient _client = new WebClient();
        string _imageUrl;
        string _saveFolderPath;
        int _from;
        int _to;
        int _index;

        public OotsDownloader()
        {
            InitializeComponent();
            txtLocation.Text = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "Order of the Stick Comics");
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            _saveFolderPath = txtLocation.Text;
            _from = Int32.Parse(txtFrom.Text);
            _to = Int32.Parse(txtTo.Text);
            if (_from > _to)
            {
                MessageBox.Show("Specify a valid comic issue range!");
                return;
            }
            _index = _from;
            progressBar.Minimum = 0;
            progressBar.Maximum = _to - _from + 1;
            DownloadPicture();
        }

        private async void DownloadPicture()
        {
            Directory.CreateDirectory(_saveFolderPath);

            while (true)
            {
                if (_index >= 338)
                {
                    var html = await _client.DownloadStringTaskAsync(Properties.Settings.Default.OotsComicsRoot + String.Format("{0:D4}", _index) + ".html");
                    var partialUrl = Regex.Match(html, @"src=""/comics/images/(.+)"">").Groups[1].Value;
                    _imageUrl = Properties.Settings.Default.OotsImagesRoot + partialUrl;
                }
                else
                {
                    _imageUrl = Properties.Settings.Default.OotsImagesRoot + @"oots" + String.Format("{0:D4}", _index) + ".gif";
                }

                var imageFileName = @"oots" + String.Format("{0:D4}", _index) + ".gif";
                await _client.DownloadFileTaskAsync(new Uri(_imageUrl), Path.Combine(_saveFolderPath, imageFileName));
                if (_index != _to)
                {
                    _index++;
                    progressBar.Increment(1);
                    continue;
                }

                progressBar.Increment(1);
                MessageBox.Show("Oots download completed!");
                progressBar.Value = 0;
                break;
            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            var result = folderBrowserDialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                txtLocation.Text = folderBrowserDialog.SelectedPath + @"\";
            }
        }
    }
}